using System;
using System.Collections.Generic;
using System.Html;
using jQueryApi;

namespace Loa
{

    public class TimerGadget
    {
        private readonly TimerGadgetOptions _opt;

        public TimerGadget(TimerGadgetOptions options)
        {
            _opt = options;
            if (_opt.Done)
            {
                Cancel();
                return;
            }
            _opt.StartTm = (new Date()).GetTime();
            _opt.StopTm = _opt.StartTm + _opt.Duration;
            if (_opt.Start != null)
                _opt.Start(_opt);
            _opt.Timer = Window.SetInterval(Trigger, _opt.Interval);
        }

        public void Trigger()
        {
            _opt.Tick++;
            if (_opt.Trigger != null)
                _opt.Trigger(_opt);
            if ((new Date()).GetTime() > _opt.StopTm)
            {
                Window.ClearInterval(_opt.Timer);
                if (_opt.Stop != null)
                    _opt.Stop(_opt);
                _opt.Done = true;
            }
        }

        public void Cancel()
        {
            _opt.Done = true;
            Window.ClearInterval(_opt.Timer);
            if (_opt.Cancel != null)
                _opt.Cancel(_opt);
        }
    }

    public sealed class TimerGadgetOptions
    {
        public int StartTm;
        public int StopTm;
        public int Tick;
        public int Interval = 1000;
        public int Duration = 1000;
        public Action<TimerGadgetOptions> Start;
        public Action<TimerGadgetOptions> Stop;
        public Action<TimerGadgetOptions> Trigger;
        public Action<TimerGadgetOptions> Cancel;
        public List<int> Marks;
        public int Timer;
        public jQueryObject Element;
        public bool Done;
    }
}
